//
//  MusicPlayViewController.m
//  FuncFanc
//
//  Created by careate-hubing on 2021/7/1.
//  Copyright © 2021 huhu. All rights reserved.
//

#import "MusicPlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "MusicModel.h"

@interface MusicPlayViewController ()<UITableViewDelegate,UITableViewDataSource,AVAudioPlayerDelegate>
@property (nonatomic,strong) AVAudioPlayer *audioPlayer;
@property (nonatomic,strong) NSMutableArray *musicList;
@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,assign) NSInteger currentIndex;
@property (nonatomic,assign) PlayOrder myOrder;
@property (nonatomic,strong) UISegmentedControl *seg;
@end

@implementation MusicPlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的音乐";
    [self.view addSubview:self.tableview];
    self.myOrder = RandomPlay;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"Add all" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(resetMusicListOrder) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:button];;
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.navigationItem.titleView = self.seg;
}

-(UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        [self.view addSubview:_tableview];
        [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
    }
    return _tableview;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.00001f;
}

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section{
    return 0.000001f;
}

// 单曲循环，  列表顺序循环播放 ， 随机播放
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.musicList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass([UITableViewCell class])];
    }
    MusicModel *music = self.musicList[indexPath.row];
    cell.textLabel.text = music.musicName;
    cell.detailTextLabel.text = music.singer;
    return cell;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.musicList removeObjectAtIndex:indexPath.row];
    [self.tableview beginUpdates];
    [self.tableview deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableview endUpdates];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicModel *music = self.musicList[indexPath.row];
    [[AppDelegate sharedAppDelegate].floatView addMusicModelToPlayListWith:@[music]];
//    [self playWithModel:music];
}

-(void)playWithModel:(MusicModel *)music
{
    if (self.audioPlayer) {
        [self.audioPlayer stop];
        self.audioPlayer = nil;
    }
    NSInteger index = [self.musicList indexOfObject:music];
    self.currentIndex = index;
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:music.musicPath ofType:music.audioCompressionFormat];

    NSError *error = nil;

    //初始化播放器
    _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:[music.musicPath stringByUrlEncoding]] error:&error];

    //是否循环播放
    _audioPlayer.numberOfLoops = 0;

    //把播放文件加载到缓存中（注意：即使在播放之前音频文件没有加载到缓冲区程序也会隐式调用此方法。）
    [_audioPlayer prepareToPlay];

    //设置代理，监听播放状态(例如:播放完成)
    _audioPlayer.delegate = self;

    // 设置音频会话模式，后台播放
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    // 添加通知(输出改变通知)  ios 6.0 后
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:nil];
    if (error) {
//            NSAssert(YES,"音乐初始化过程报错");
    }
    [self.audioPlayer play];
}
// 当前歌曲播放完成
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSInteger musicIndex = 0;
    switch (self.myOrder) {
        case SinglePlay:
            return;
            break;
        case SingleCirclePlay:
            musicIndex = self.currentIndex;
            break;;
        case  AscendCirclePlay:
        case  RandomPlay:
            musicIndex = self.currentIndex + 1;
            if (musicIndex > self.musicList.count) {
                musicIndex = 0;
            }
            break;
//        case RandomPlay:
//            musicIndex = [QHCommonTool getRamdomNumberUnder:self.musicList.count noNumber:self.currentIndex];
//            break;
        default:
            break;
    }
    
    MusicModel *nextMusic = self.musicList[musicIndex];
    [self playWithModel:nextMusic];
}

-(void)resetMusicListOrder
{
    
//    NSArray *result = [self.musicList sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
//        int seed = arc4random_uniform(2);
//        MusicModel *model1 = (MusicModel *)obj1;
//        MusicModel *model2 = (MusicModel *)obj2;
//
//        if (seed) {
//            return [model1.musicPath compare:model2.musicPath];
//        }else{
//            return [model2.musicPath compare:model1.musicPath];
//        }
//    }];
//    [self.musicList removeAllObjects];
//    [self.musicList addObjectsFromArray:result];
//    [self.tableview reloadData];
    NSString *song_name = @"";
    for (MusicModel *model in self.musicList) {
        song_name = [song_name stringByAppendingFormat:@"%@\n",model.musicName];
    }
    NSLog(@"%@",song_name);
//    [[AppDelegate sharedAppDelegate].floatView  addMusicModelToPlayListWith:self.musicList];
}

-(NSMutableArray *)musicList{
    if (!_musicList) {
        _musicList = [[MusicModel loadMusicFromSandBox] mutableCopy];
    }
    return _musicList;
}

-(UISegmentedControl *)seg{
    if (!_seg) {
        _seg = [[UISegmentedControl alloc]initWithItems:@[@"flac",@"mp3",@"纯音乐",@"歌曲",@"华语",@"英文"]];
        _seg.tintColor = [UIColor systemBlueColor];
        _seg.selectedSegmentIndex = 0;
        [_seg addTarget:self action:@selector(segChangeIndex) forControlEvents:UIControlEventValueChanged];
    }
    return _seg;
}

-(void)segChangeIndex{
    
    
    
}

@end
